package com.minimalist.lindi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.minimalist.common.config.exception.BusinessException;
import com.minimalist.common.config.mybatis.bo.PageResp;
import com.minimalist.common.entity.basic.enums.RespEnum;
import com.minimalist.common.entity.basic.enums.StatusEnum;
import com.minimalist.common.entity.basic.vo.file.FileUpdateStatusVO;
import com.minimalist.common.entity.basic.vo.file.FileVO;
import com.minimalist.common.entity.lindi.po.LindiLaws;
import com.minimalist.common.entity.lindi.vo.laws.LindiLawsQueryVO;
import com.minimalist.common.entity.lindi.vo.laws.LindiLawsVO;
import com.minimalist.common.feign.client.basic.FileFeignClient;
import com.minimalist.common.response.R;
import com.minimalist.common.utils.TextUtil;
import com.minimalist.common.utils.UnqIdUtil;
import com.minimalist.lindi.mapper.LindiLawsMapper;
import com.minimalist.lindi.service.LindiLawsService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 林地指标交易平台_政策法规表 服务层实现。
 *
 * @author 11987
 * @since 2025-06-12
 */
@Service
public class LindiLawsServiceImpl extends ServiceImpl<LindiLawsMapper, LindiLaws> implements LindiLawsService{

    @Autowired
    private LindiLawsMapper mapper;

    @Autowired
    private FileFeignClient fileFeignClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addLaws(LindiLawsVO lawsVO){
        LindiLaws laws = BeanUtil.copyProperties(lawsVO, LindiLaws.class);
        //政策法规ID
        long lawsId = UnqIdUtil.uniqueId();
        laws.setLawsId(lawsId);
        //内容处理 -> 编码
        laws.setLawsContent(TextUtil.encode(lawsVO.getLawsContent()));
        //插入
        int insertCount = mapper.insert(laws, true);
        Assert.isTrue(insertCount > 0
                , () -> new BusinessException(RespEnum.FAILED.getDesc()));
        //政策法规相关文件处理
        fileStatusHandler(null, lawsVO, StatusEnum.STATUS_1.getCode());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteLawsByLawsId(Long lawsId){
        //查询政策法规
        LindiLaws laws = mapper.selectLawsByLawsId(lawsId);
        Assert.notNull(laws, () -> new BusinessException("政策法规不存在"));
        //政策法规相关文件处理
        fileStatusHandler(null
                , BeanUtil.copyProperties(laws, LindiLawsVO.class)
                , StatusEnum.STATUS_0.getCode());
        //删除政策法规
        mapper.deleteLawsByLawsId(lawsId);
    }

    @Override
    public void updateLawsByLawsId(LindiLawsVO lawsVO){
        //查询政策法规
        LindiLaws laws = mapper.selectLawsByLawsId(lawsVO.getLawsId());
        Assert.notNull(laws, () -> new BusinessException("政策法规不存在"));
        LindiLaws newLaws = BeanUtil.copyProperties(lawsVO, LindiLaws.class);
        //内容处理 -> 编码
        newLaws.setLawsContent(TextUtil.encode(newLaws.getLawsContent()));
        //修改
        mapper.updateLawsByLawsId(newLaws);
        //政策法规相关文件处理
        fileStatusHandler(laws, BeanUtil.copyProperties(newLaws, LindiLawsVO.class), null);
    }

    @Override
    public PageResp<LindiLawsVO> getPageLawsList(LindiLawsQueryVO queryVO){
        //分页查询
        Page<LindiLaws> lawsPage = mapper.selectPageLawsList(queryVO);
        //数据转换
        List<LindiLawsVO> lawsVOList = BeanUtil.copyToList(lawsPage.getRecords()
                , LindiLawsVO.class);

        // 批量获取文件信息
        if (CollectionUtil.isNotEmpty(lawsVOList)){
            // 收集所有文件ID
            List<String> fileIdStrings = lawsVOList.stream()
                    .map(LindiLawsVO::getLawsFileId)
                    .filter(ObjectUtil::isNotNull)
                    .distinct()
                    .collect(java.util.stream.Collectors.toList());

            if (CollectionUtil.isNotEmpty(fileIdStrings)){
                // 解析文件ID字符串为Long列表
                List<Long> fileIds = fileIdStrings.stream()
                        .flatMap(fileIdStr -> java.util.Arrays.stream(fileIdStr.split(",")))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .map(Long::valueOf)
                        .distinct()
                        .collect(java.util.stream.Collectors.toList());

                if (CollectionUtil.isNotEmpty(fileIds)){
                    // 批量获取文件信息
                    R<List<FileVO>> filesResult = fileFeignClient.getFileListByFileIds(fileIds);
                    if (filesResult.getCode().equals(RespEnum.SUCCESS.getCode()) &&
                            CollectionUtil.isNotEmpty(filesResult.getData())){
                        // 创建文件ID到文件对象的映射
                        java.util.Map<Long, FileVO> fileMap = filesResult.getData().stream()
                                .collect(java.util.stream.Collectors.toMap(FileVO::getFileId, file -> file));

                        // 为每个政策法规设置对应的文件信息
                        lawsVOList.forEach(item -> {
                            if (ObjectUtil.isNotNull(item.getLawsFileId())){
                                List<FileVO> attachmentFiles = java.util.Arrays.stream(item.getLawsFileId().split(","))
                                        .map(String::trim)
                                        .filter(s -> !s.isEmpty())
                                        .map(Long::valueOf)
                                        .map(fileMap::get)
                                        .filter(ObjectUtil::isNotNull)
                                        .collect(java.util.stream.Collectors.toList());
                                item.setLawsFiles(attachmentFiles);
                            }
                        });
                    }
                }
            }
        }

        return new PageResp<>(lawsVOList, lawsPage.getTotalRow());
    }

    @Override
    public LindiLawsVO getLawsByLawsId(Long lawsId){
        LindiLaws laws = mapper.selectLawsByLawsId(lawsId);
        //内容 -> 解码
        laws.setLawsContent(TextUtil.decode(laws.getLawsContent()));
        Assert.notNull(laws, () -> new BusinessException("政策法规不存在"));
        LindiLawsVO lindiLawsVO = BeanUtil.copyProperties(laws, LindiLawsVO.class);
        if (laws.getLawsFileId() != null){
            // 解析文件ID字符串
            List<Long> fileIds = java.util.Arrays.stream(laws.getLawsFileId()
                            .split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Long::valueOf)
                    .collect(java.util.stream.Collectors.toList());

            if (CollectionUtil.isNotEmpty(fileIds)){
                R<List<FileVO>> result = fileFeignClient.getFileListByFileIds(fileIds);
                Assert.isTrue(result.getCode() == HttpStatus.HTTP_OK
                        && result.getData() != null, () -> new BusinessException(
                        "获取政策法规文件失败"));
                lindiLawsVO.setLawsFiles(result.getData());
            }
        }
        return lindiLawsVO;
    }

    @Override
    public PageResp<LindiLawsVO> getWebsiteLawsList(LindiLawsQueryVO queryVO){
        // 前台网站只查询状态为1（已发布）的政策法规
        queryVO.setStatus(StatusEnum.STATUS_1.getCode());
        Page<LindiLawsVO> lawsPage = mapper.selectWebsiteLawsList(queryVO);
        List<LindiLawsVO> lawsVOList = lawsPage.getRecords();

        if (CollectionUtil.isNotEmpty(lawsVOList)){
            // 收集所有文件ID
            List<String> fileIdStrings = lawsVOList.stream()
                    .map(LindiLawsVO::getLawsFileId)
                    .filter(ObjectUtil::isNotNull)
                    .distinct()
                    .collect(java.util.stream.Collectors.toList());

            if (CollectionUtil.isNotEmpty(fileIdStrings)){
                // 解析文件ID字符串为Long列表
                List<Long> fileIds = fileIdStrings.stream()
                        .flatMap(fileIdStr -> java.util.Arrays.stream(fileIdStr.split(",")))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .map(Long::valueOf)
                        .distinct()
                        .collect(java.util.stream.Collectors.toList());

                if (CollectionUtil.isNotEmpty(fileIds)){
                    // 批量获取文件信息
                    R<List<FileVO>> filesResult = fileFeignClient.getFileListByFileIds(fileIds);
                    if (filesResult.getCode().equals(RespEnum.SUCCESS.getCode()) &&
                            CollectionUtil.isNotEmpty(filesResult.getData())){
                        // 创建文件ID到文件对象的映射
                        java.util.Map<Long, FileVO> fileMap = filesResult.getData().stream()
                                .collect(java.util.stream.Collectors.toMap(FileVO::getFileId, file -> file));

                        // 为每个政策法规设置对应的文件信息
                        lawsVOList.forEach(item -> {
                            if (ObjectUtil.isNotNull(item.getLawsFileId())){
                                List<FileVO> attachmentFiles = java.util.Arrays.stream(item.getLawsFileId().split(","))
                                        .map(String::trim)
                                        .filter(s -> !s.isEmpty())
                                        .map(Long::valueOf)
                                        .map(fileMap::get)
                                        .filter(ObjectUtil::isNotNull)
                                        .collect(java.util.stream.Collectors.toList());
                                item.setLawsFiles(attachmentFiles);
                            }
                        });
                    }
                }
            }
        }

        return new PageResp<>(lawsVOList, lawsPage.getTotalRow());
    }

    @Override
    public LindiLawsVO getWebsiteLawsDetail(Long lawsId){
        LindiLaws laws = mapper.selectWebsiteLawsDetail(lawsId);
        Assert.notNull(laws, () -> new BusinessException("政策法规不存在或未发布"));
        
        //内容 -> 解码
        laws.setLawsContent(TextUtil.decode(laws.getLawsContent()));
        LindiLawsVO lindiLawsVO = BeanUtil.copyProperties(laws, LindiLawsVO.class);
        
        if (laws.getLawsFileId() != null){
            // 解析文件ID字符串
            List<Long> fileIds = java.util.Arrays.stream(laws.getLawsFileId()
                            .split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Long::valueOf)
                    .collect(java.util.stream.Collectors.toList());

            if (CollectionUtil.isNotEmpty(fileIds)){
                R<List<FileVO>> result = fileFeignClient.getFileListByFileIds(fileIds);
                if (result.getCode() == HttpStatus.HTTP_OK && result.getData() != null){
                    lindiLawsVO.setLawsFiles(result.getData());
                }
            }
        }
        return lindiLawsVO;
    }

    /**
     * 修改政策法规相关的文件信息
     *
     * @param oldLaws    政策法规(旧)
     * @param newLaws    政策法规(新)
     * @param fileStatus 文件状态
     */
    private void fileStatusHandler(LindiLaws oldLaws, LindiLawsVO newLaws, Integer fileStatus){
        //政策法规插入、删除的文件处理
        if (ObjectUtil.isNull(oldLaws)){
            //处理富文本编辑器中的图片，富文本内容解码
            String decodeOldContent = TextUtil.decode(newLaws.getLawsContent());
            List<String> imgUrlList = TextUtil.getImgUrlByRichText(decodeOldContent);
            if (CollectionUtil.isNotEmpty(imgUrlList)){
                //将富文本中的图片的状态置为已使用
                FileUpdateStatusVO fileUpdateStatusVO = new FileUpdateStatusVO(StpUtil.getLoginIdAsLong(), imgUrlList, fileStatus);
                fileFeignClient.updateStatusByFileUrl(fileUpdateStatusVO);
            }
        } else{
            //旧政策法规富文本中的图片
            String decodeOldContent = TextUtil.decode(oldLaws.getLawsContent());
            List<String> oldContentImgUrlList = TextUtil.getImgUrlByRichText(decodeOldContent);
            //将旧政策法规富文本中的图片状态置为未使用
            if (CollectionUtil.isNotEmpty(oldContentImgUrlList)){
                FileUpdateStatusVO fileUpdateStatusVO = new FileUpdateStatusVO(
                        StpUtil.getLoginIdAsLong(), oldContentImgUrlList
                        , StatusEnum.STATUS_0.getCode());
                fileFeignClient.updateStatusByFileUrl(fileUpdateStatusVO);
            }
            //新政策法规富文本中的图片
            String decodeNewContent = TextUtil.decode(newLaws.getLawsContent());
            List<String> newContentImgUrlList = TextUtil.getImgUrlByRichText(decodeNewContent);
            //将新政策法规富文本中的图片状态置为已使用
            if (CollectionUtil.isNotEmpty(newContentImgUrlList)){
                FileUpdateStatusVO fileUpdateStatusVO = new FileUpdateStatusVO(
                        StpUtil.getLoginIdAsLong(), newContentImgUrlList
                        , StatusEnum.STATUS_1.getCode());
                fileFeignClient.updateStatusByFileUrl(fileUpdateStatusVO);
            }
        }
    }
}
